<template>
  <!--备机申请页面-->
  <div>
    <!--查询条件区域-->
    <div>
      <el-form :inline="true">
        <el-form-item>
          <el-select v-model="searchDto.applicationStatus" clearable placeholder="申请状态">
            <el-option v-for="item in applicationStatusList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData()">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()"
                     v-if="this.roleType === '1' || (this.roleType === '2' && this.officeType === '0') ">备机申请
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--一览显示区域-->
    <custom-table
      :columns="columnListInfo"
      :data="standbyApplyList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>
    <!--备机申请模态框-->
    <el-dialog title="备机申请" center :visible.sync="standbyApplyFormVisible" wdith="100%" :close-on-click-modal="false"
               :before-close="onBtnCancel">
      <el-form class="form-horizontal" :model="applyDto" :rules="applyRules" label-width="120px"
               ref="applyForm">
        <el-form-item label="申请人" prop="name">
          <el-input v-model.trim="applyDto.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="接收省份" prop="provinceCode">
          <el-input v-model.trim="applyDto.provinceName" :disabled="true" v-if="this.roleType === '2'">{{}}</el-input>
          <el-select v-model="applyDto.provinceCode" placeholder="接收省份" @change="onGetReceiver"
                     v-if="this.roleType === '1'">
            <el-option
              v-for="item in allProvinceOffice"
              :key="item.provinceCode"
              :label="item.province"
              :value="item.provinceCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接收人" prop="receiverName">
          <el-input v-model.trim="applyDto.receiverName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="接收人联系方式" prop="receiverTel">
          <el-input v-model.trim="applyDto.receiverTel" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="接收人详细地址" prop="receiverAddress">
          <el-input v-model.trim="applyDto.receiverAddress" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="型号" prop="modelId">
          <el-select v-model.number="applyDto.modelId" placeholder="请选择型号" @change="onItemName">
            <el-option
              v-for="item in modelOptions"
              :key="item.id"
              :label="item.code"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="itemName">
          <el-input v-model.trim="applyDto.itemName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model.number="applyDto.unit" placeholder="请选择单位">
            <el-option key="1" label="台" value="台"></el-option>
            <el-option key="2" label="套" value="套"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model.number="applyDto.num" :min="1" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="额度类型" prop="isOver">
          <el-radio-group v-model="applyDto.isOver">
            <el-radio :label="0">额度内(0.3%)</el-radio>
            <el-radio :label="1">额度外</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因说明" prop="remark">
          <el-input v-model="applyDto.remark" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <div style="position: relative">
            <el-button @click="onBtnCancel()" style="position:absolute;top:2px;left:60%">取消
            </el-button>
            <el-button id="1" type="primary" @click="onBtnSubmit()" style="position:absolute;top:2px;left:80%"
                       :disabled="isApply">确认
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--申请详情模态框-->
    <el-dialog title="申请详情" center :visible.sync="applyDetailVisible" wdith="100%" :close-on-click-modal="false">
      <el-steps align-center :active="applyStep" finish-status="success" :process-status="processStatus">
        <el-step title="申请备机"></el-step>
        <el-step title="审核"></el-step>
        <el-step title="审批"></el-step>
        <el-step title="发放"></el-step>
      </el-steps>
      <div v-if="applyStep>=1">
        <h4>审核结果：</h4>
        <custom-table
          :columns="columnDailogAudit"
          :data="applyAuditDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
      <div v-if="applyStep>=2">
        <h4>审批结果：</h4>
        <custom-table
          :columns="columnDailogApprove"
          :data="applyApproveDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {parseTime} from '@/utils'
  import {
    getRoleType,
    getOfficeType,
    getName,
    getUserId,
    getProvinceName,
    getProvinceCode
  } from '@/utils/token'
  import {apiGetReceiver} from '@/api/basic/info/inside/office'
  import {apiApply, apiGetItem, apiSpareSelfList, apiSpareSelfDetail} from '@/api/standby/index'
  import {apiGetModelList, apiGetProvinceOffice, apiGetApplicationStatus} from '@/api/dictionary'

  export default {
    components: {
      CustomTable
    },
    created () {
      this.def()
      this.getAllProvinceOffice()
      this.getSelfApplyList()
    },
    data () {
      return {
        // 申请状态List
        applicationStatusList: this.getApplicationStatusList(),
        // 一览页面的表单列
        columnListInfo: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '申请单号', name: 'applicationNo', width: '200', align: 'center'},
          {label: '申请状态', name: 'applicationStatus', width: '100', align: 'center'},
          {label: '产品型号', name: 'model', width: '150', align: 'center'},
          {label: '产品类型', name: 'itemName', width: '100', align: 'center'},
          {label: '数量', name: 'num', width: '100', align: 'center'},
          {label: '额度', name: 'isOver', width: '100', align: 'center'},
          {label: '申请人', name: 'proposerName', width: '100', align: 'center'},
          {label: '接收人姓名', name: 'receiverName', width: '100', align: 'center'},
          {label: '接收人联系电话', name: 'receiverTel', width: '130', align: 'center'},
          {label: '接收人地址', name: 'receiverAddress', width: '250', align: 'center'},
          {label: '原因说明', name: 'remark', width: '250', align: 'center'},
          {label: '申请日期', name: 'applicationDate', width: '160', align: 'center', formatter: this.formatTime}
        ],
        // 一览页面的操作栏
        operationColumn: {
          width: '100',
          operations: [
            {name: '详情', callback: this.getDetailSelfApply}
          ]
        },
        // 申请详情模态框审核的表单列
        columnDailogAudit: [
          {label: '审核人', name: 'name', width: '100', align: 'center'},
          {label: '审核时间', name: 'time', width: '180', align: 'center', formatter: this.formatTime},
          {label: '审核结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        // 申请详情模态框审批的表单列
        columnDailogApprove: [
          {label: '审批人', name: 'name', width: '100', align: 'center'},
          {label: '审批时间', name: 'time', width: '180', align: 'center', formatter: this.formatTime},
          {label: '审批结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        // 一览页面信息List
        standbyApplyList: [],
        // 角色类型
        roleType: getRoleType(),
        // 办事处类型：省级，市级
        officeType: getOfficeType(),
        // 省办事处List
        allProvinceOffice: [],
        // 备机申请DTO
        applyDto: {
          proposerId: undefined,
          proposerName: '',
          provinceName: '',
          provinceCode: '',
          receiverName: '',
          receiverTel: '',
          receiverAddress: '',
          itemName: '',
          modelId: '',
          num: '',
          unit: undefined,
          remark: '',
          name: '',
          province: '',
          isOver: ''
        },
        // 备机申请模态框默认隐藏
        standbyApplyFormVisible: false,
        // 申请步骤条默认隐藏
        applyDetailVisible: false,
        // 初始进度状态
        processStatus: 'wait',
        // 进度状态值
        applyStep: 0,
        // 审核DTO信息
        applyAuditDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        // 审批DTO信息
        applyApproveDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        tableLoadingFlag: false,
        pagination: this.getData(this.getSelfApplyList),
        provinceCode: '',
        // 型号List
        modelOptions: this.selectedModelInit(),
        // 备机申请成功Flag
        isApply: false,
        // 查询用DTO
        searchDto: {
          applicationStatus: ''
        },
        // List查询条件
        listQuery: {
          status: undefined
        },
        // 检证规则
        applyRules: {
          itemName: [
            {required: true, message: '请填写产品名称', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          modelId: [{type: 'number', required: true, message: '请填写型号', trigger: 'change'}],
          unit: [{required: true, message: '请选择单位', trigger: 'change'}],
          remark: [
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'},
            {required: true, message: '请填写申请原因说明', trigger: 'blur'}
          ],
          isOver: [{type: 'number', required: true, message: '请选择额度类型', trigger: 'change'}]
        }
      }
    },
    methods: {
      // 获取申请状态List
      getApplicationStatusList () {
        apiGetApplicationStatus().then(rsp => {
          this.applicationStatusList = rsp.data
        })
      },
      // 日期format
      formatTime (row, column, cellValue) {
        return parseTime(cellValue)
      },
      def () {
        // 获取申请人姓名
        this.applyDto.name = getName()
        if (this.roleType === '2') {
          this.applyDto.provinceName = getProvinceName()
          this.applyDto.provinceCode = getProvinceCode()
          this.onGetReceiver()
        }
      },
      // 获取省办事处的物流接收信息
      onGetReceiver () {
        this.applyDto.receiveProvince = this.applyDto.provinceCode
        apiGetReceiver(this.applyDto).then(response => {
          this.applyDto.receiverName = response.data[0].logisticsContact
          this.applyDto.receiverTel = response.data[0].logisticsTel
          this.applyDto.receiverAddress = response.data[0].logisticsAddr
        })
      },
      // 获取拥有省办事处的省份
      getAllProvinceOffice () {
        apiGetProvinceOffice().then(response => {
          this.allProvinceOffice = response.data
        })
      },
      // 获取个人备机申请一览
      getSelfApplyList (listquery) {
        if (this.listQuery.status !== undefined) {
          listquery.status = this.listQuery.status
        }
        apiSpareSelfList(listquery).then(response => {
          this.standbyApplyList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        })
      },
      // 审核结果
      formatStatus (row, column, cellValue) {
        if (cellValue === 1) {
          return '不通过'
        }
        return '通过'
      },
      // 备机申请框弹出
      handleAdd () {
        this.standbyApplyFormVisible = true
        this.isApply = false
      },
      // 获取一条备机申请的详细信息
      getDetailSelfApply (row) {
        apiSpareSelfDetail(row.id).then(response => {
          if (response.data.applicationStatus === 1) {
            // 已提交申请，待审核
            this.applyStep = 0
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 2) {
            // 已通过审核，待审批
            this.applyStep = 1
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 3 || response.data.applicationStatus === 4) {
            // 已通过审批，待发放
            this.applyStep = 2
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 5) {
            // 设备已全部发放
            this.applyStep = 3
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 6 && (response.approve === undefined || response.approve === null)) {
            // 未通过审核
            this.applyStep = 1
            this.processStatus = 'error'
          } else if (response.data.applicationStatus === 6 && response.approve !== undefined && response.approve !== null) {
            // 未通过审批
            this.applyStep = 2
            this.processStatus = 'error'
          }
          if (this.applyStep >= 1) {
            this.applyAuditDetail[0].name = response.audit.name
            this.applyAuditDetail[0].time = response.audit.approveDate
            this.applyAuditDetail[0].result = response.audit.result
            this.applyAuditDetail[0].reason = response.audit.cause
          }
          if (this.applyStep >= 2) {
            this.applyApproveDetail[0].name = response.approve.name
            this.applyApproveDetail[0].time = response.approve.approveDate
            this.applyApproveDetail[0].result = response.approve.result
            this.applyApproveDetail[0].reason = response.approve.cause
          }
          this.applyDetailVisible = true
        })
      },
      // 根据选择的型号获取类型
      onItemName (listQuery) {
        apiGetItem(listQuery).then(response => {
          this.applyDto.itemName = response.data
        })
      },
      // 型号选择初始化
      selectedModelInit () {
        apiGetModelList().then(response => {
          let modelList = response.data
          let model = []
          let temp = {}
          for (let i in modelList) {
            if (!temp[modelList[i].code]) {
              temp[modelList[i].code] = modelList[i].id
            }
          }
          for (let k in temp) {
            model.push({'code': k, 'id': temp[k]})
          }
          this.modelOptions = model
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 新增备机申请
      onBtnSubmit () {
        this.$refs['applyForm'].validate((valid) => {
          if (valid) {
            let dto = {
              proposerId: getUserId(),
              proposerName: getName(),
              provinceName: this.applyDto.provinceName,
              provinceCode: this.applyDto.provinceCode,
              receiverName: this.applyDto.receiverName,
              receiverTel: this.applyDto.receiverTel,
              receiverAddress: this.applyDto.receiverAddress,
              itemName: this.applyDto.itemName,
              modelId: this.applyDto.modelId,
              num: this.applyDto.num,
              unit: this.applyDto.unit,
              remark: this.applyDto.remark,
              name: this.applyDto.name,
              province: this.applyDto.province,
              isOver: this.applyDto.isOver
            }
            apiApply(dto).then(() => {
              this.getSelfApplyList()
              this.onBtnCancel()
              this.$message({
                showClose: true,
                message: '备机申请成功',
                type: 'success'
              })
            })
            this.isApply = true
          } else {
            return false
          }
        })
      },
      // 备机申请模态框:取消操作
      onBtnCancel () {
        // 清除From数据
        this.$refs['applyForm'].resetFields()
        // 备机申请模态框Flag为false
        this.standbyApplyFormVisible = false
      },
      // 查询操作
      searchData () {
        this.listQuery.status = this.searchDto.applicationStatus
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getSelfApplyList(this.listQuery)
      }
    }
  }
</script>
